package cn.com.anysdk.core.log;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

/**
 * 操作日志工具类
 * 用于记录各种操作的日志，支持 MDC 上下文管理
 */
@Slf4j
public class OperationLogger {
    private static final String OPERATION_TYPE = "operationType";
    private static final String SERVICE = "service";
    private static final String PATH = "path";
    private static final String DURATION = "duration";
    private static final String SIZE = "size";
    private static final String IS_PRIVATE = "isPrivate";
    private static final String REQUEST_ID = "requestId";

    /**
     * 记录操作开始
     * @param operationType 操作类型
     * @param service 服务名称
     * @param path 操作路径
     */
    public static void logOperationStart(String operationType, String service, String path) {
        MDC.put(OPERATION_TYPE, operationType);
        MDC.put(SERVICE, service);
        MDC.put(PATH, path);
        log.info("Operation started - type: {}, service: {}, path: {}", operationType, service, path);
    }

    /**
     * 记录操作结束
     * @param duration 操作耗时（毫秒）
     * @param size 数据大小（字节）
     * @param isPrivate 是否私有操作
     * @param requestId 请求ID
     */
    public static void logOperationEnd(long duration, long size, boolean isPrivate, String requestId) {
        MDC.put(DURATION, String.valueOf(duration));
        MDC.put(SIZE, String.valueOf(size));
        MDC.put(IS_PRIVATE, String.valueOf(isPrivate));
        MDC.put(REQUEST_ID, requestId);
        log.info("Operation completed - duration: {}ms, size: {}bytes, private: {}, requestId: {}",
                duration, size, isPrivate, requestId);
        clearContext();
    }

    /**
     * 记录操作错误
     * @param errorMessage 错误信息
     * @param e 异常对象
     */
    public static void logOperationError(String errorMessage, Throwable e) {
        log.error("Operation failed - error: {}", errorMessage, e);
        clearContext();
    }

    /**
     * 清除日志上下文
     */
    private static void clearContext() {
        MDC.remove(OPERATION_TYPE);
        MDC.remove(SERVICE);
        MDC.remove(PATH);
        MDC.remove(DURATION);
        MDC.remove(SIZE);
        MDC.remove(IS_PRIVATE);
        MDC.remove(REQUEST_ID);
    }
}